<template>
	<view>
		<roc-navbar :title="urlQuery.menuTitle"></roc-navbar>
		<view class="detail-cont u-p-20">
			<view class="row" v-for="(item, index) in detailList" :key="index">
				<template v-if="item.type == 'select' || item.type == 'checkbox'">
					<text class="title">{{ item.name }}：</text>
					<text v-for="(vItem, vIndex) in String(item.value).split(',')" :key="vIndex">
						<text v-if="keyValueDatasObj[item.field]">{{ keyValueDatasObj[item.field][vItem] }}</text>
						<text v-if="vIndex < String(item.value).split(',').length - 1">,</text>
					</text>
				</template>
				<template v-else-if="item.type == 'radio'">
					<text class="title">{{ item.name }}：</text>
					<text v-if="keyValueDatasObj[item.field]">{{ keyValueDatasObj[item.field][item.value] }}</text>
				</template>
				<template v-else-if="item.type == 'upload'">
					<text class="title">{{ item.name }}：</text>
					<view class="image-box">
						<view class="roc-image" v-for="(imgUrlItem, imgUrlIndex) in item.value" :key="imgUrlIndex">
							<template  v-if="item.props.uploadType == 'file'">
								<u-icon name="file-text" size="120" @click="handleDownload(imgUrlItem)"></u-icon>
							</template>
							<template v-else>
								<u--image :src="imgUrlItem" width="160" height="160" @click="previewOpen(imgUrlItem)"></u--image>
							</template>
						</view>
					</view>
				</template>
				<template v-else-if="item.type == 'cascader'">
					<text class="title">{{ item.name }}：</text>
					<text v-for="(vItem, vIndex) in String(item.value).split(',')" :key="vIndex">
						<text v-if="keyValueDatasObj[item.field]">{{ keyValueDatasObj[item.field][vItem] }}</text>
						<text v-if="vIndex < String(item.value).split(',').length - 1">/</text>
					</text>
				</template>
				<template v-else-if="item.type == 'tree'">
					<text class="title">{{ item.name }}：</text>
					<text>{{ item.value }}</text>
				</template>
				<template v-else-if="item.type == 'fc-editor'">
					<text class="title">{{ item.name }}：</text>
					<text v-html="item.value"></text>
				</template>
				<template v-else-if="item.type == 'input'">
					<text class="title">{{ item.name }}：</text>
					<template v-if="item.props && item.props.type == 'number'">
						{{ item.value | kgRule }}
					</template>
					<template v-else>
						{{ item.value }}
					</template>
					<text v-if="item.children != undefined && item.children[0].children[0] != ''">
						({{ item.children[0].children[0] }})
					</text>
				</template>
				<template v-else-if="item.type == 'datePicker'">
					<text class="title">{{ item.name }}：</text>
					<text>{{ item.value == '2000-01-01T00:00:00' ? '' : item.value }}</text>
				</template>
				<template v-else>
					<text class="title">{{ item.name }}：</text>
					<text>{{ item.value }}</text>
				</template>
			</view>
		</view>
		<!-- 子表 -->
		<view>
			<template v-if="modelDetail.sub_table && modelSubTableDetail.is_detail == '1'">
				<view class="sub-table-main">
					<view class="line"></view>
					<view class="title-box u-p-20">
						<view class="sub-table-title">{{ modelSubTableDetail.name }}</view>
					</view>
					<!-- 子表内容 -->
					<view class="sub-table-cont u-p-20">
						<template v-if="subTableList.length">
							<view v-for="(row, rowIndex) in subTableList" :key="rowIndex">
								<uni-collapse>
									<uni-collapse-item>
										<template v-slot:title>
											<view class="row-box">
												<view class="text" v-for="item in subTableFieldList.slice(0, 2)" :key="item.field">
													<!-- 单元格显示内容处理 -->
													<template v-if="item.type == 'select' || item.type == 'checkbox'">
														<text class="name">{{ item.title }}:</text>
														<text
															v-for="(vItem, vIndex) in row[item.field].split(',')"
															:key="vIndex"
															:class="
																keyValueDatasObj[item.field] && keyValueDatasObj[item.field][`class${row[item.field]}`]
															"
														>
															<text v-if="keyValueDatasObj[item.field]">{{ keyValueDatasObj[item.field][vItem] }}</text>
															<text v-if="vIndex < row[item.field].split(',').length - 1">,</text>
														</text>
													</template>
													<template v-else-if="item.type == 'radio'">
														<text class="name">{{ item.title }}:</text>
														<text
															:class="
																keyValueDatasObj[item.field] && keyValueDatasObj[item.field][`class${row[item.field]}`]
															"
														>
															<text v-if="keyValueDatasObj[item.field]">{{ keyValueDatasObj[item.field][row[item.field]] }}</text>
														</text>
													</template>
													<template v-else-if="item.type == 'cascader'">
														<text class="name">{{ item.title }}:</text>
														<text
															v-for="(vItem, vIndex) in row[item.field].split(',')"
															:key="vIndex"
															:class="
																keyValueDatasObj[item.field] && keyValueDatasObj[item.field][`class${row[item.field]}`]
															"
														>
															<text v-if="keyValueDatasObj[item.field]">{{ keyValueDatasObj[item.field][vItem] }}</text>
															<text v-if="vIndex < row[item.field].split(',').length - 1">/</text>
														</text>
													</template>
													<!-- 千分位 -->
													<template
														v-else-if="
															item.fieldType == 'int' ||
																(item.type == 'input' && item.props && item.props.type == 'number')
														"
													>
														<text class="name">
															{{ item.title }}
															<text v-if="item.children != undefined && item.children[0].children[0] != ''">
																({{ item.children[0].children[0] }})
															</text>
															:
														</text>
														<text>{{ row[item.field] | kgRule }}</text>
													</template>
													<template v-else-if="item.type == 'datePicker'">
														<text class="name">{{ item.title }}:</text>
														<text>{{ row[item.field] == '2000-01-01T00:00:00' ? '' : row[item.field] }}</text>
													</template>
													<template v-else>
														<text class="name">{{ item.title }}:</text>
														<text>{{ row[item.field] }}</text>
													</template>
												</view>
											</view>
										</template>
										<view class="content">
											<view class="text" v-for="item in subTableFieldList.slice(2)" :key="item.field">
												<!-- 单元格显示内容处理 -->
												<template v-if="item.type == 'select' || item.type == 'checkbox'">
													<text class="name">{{ item.title }}:</text>
													<text
														v-for="(vItem, vIndex) in row[item.field].split(',')"
														:key="vIndex"
														:class="
															keyValueDatasObj[item.field] && keyValueDatasObj[item.field][`class${row[item.field]}`]
														"
													>
														<text v-if="keyValueDatasObj[item.field]">{{ keyValueDatasObj[item.field][vItem] }}</text>
														<text v-if="vIndex < row[item.field].split(',').length - 1">,</text>
													</text>
												</template>
												<template v-else-if="item.type == 'radio'">
													<text class="name">{{ item.title }}:</text>
													<text
														:class="
															keyValueDatasObj[item.field] && keyValueDatasObj[item.field][`class${row[item.field]}`]
														"
													>
														<text v-if="keyValueDatasObj[item.field]">{{ keyValueDatasObj[item.field][row[item.field]] }}</text>
													</text>
												</template>
												<template v-else-if="item.type == 'cascader'">
													<text class="name">{{ item.title }}:</text>
													<text
														v-for="(vItem, vIndex) in row[item.field].split(',')"
														:key="vIndex"
														:class="
															keyValueDatasObj[item.field] && keyValueDatasObj[item.field][`class${row[item.field]}`]
														"
													>
														<text v-if="keyValueDatasObj[item.field]">{{ keyValueDatasObj[item.field][vItem] }}</text>
														<text v-if="vIndex < row[item.field].split(',').length - 1">/</text>
													</text>
												</template>
												<!-- 千分位 -->
												<template
													v-else-if="
														item.fieldType == 'int' ||
															(item.type == 'input' && item.props && item.props.type == 'number')
													"
												>
													<text class="name">
														{{ item.title }}
														<text v-if="item.children != undefined && item.children[0].children[0] != ''">
															({{ item.children[0].children[0] }})
														</text>
														:
													</text>
													<text>{{ row[item.field] | kgRule }}</text>
												</template>
												<template v-else-if="item.type == 'datePicker'">
													<text class="name">{{ item.title }}:</text>
													<text>{{ row[item.field] == '2000-01-01T00:00:00' ? '' : row[item.field] }}</text>
												</template>
												<template v-else>
													<text class="name">{{ item.title }}:</text>
													<text>{{ row[item.field] }}</text>
												</template>
											</view>
										</view>
									</uni-collapse-item>
								</uni-collapse>
							</view>
						</template>
						<view style="text-align: center;" v-else>
							<image src="@/static/img/nullData.png" style="width: 160rpx;height: 160rpx;"></image>
							<view style="color: #888;">暂无数据~</view>
						</view>
					</view>
				</view>
			</template>
		</view>
		<!-- 图片预览 -->
		<preview-image ref="previewImage" :imgs="previewImageList"></preview-image>
		<!-- 下载 -->
		<u-modal
			:show="downSuccessShow"
			confirmText="关闭"
			title="下载"
			:content="downSuccessStatus"
			@confirm="downSuccessClose"
			@close="downSuccessClose"
		></u-modal>
	</view>
</template>

<script>
import valueShowName from '@/mixins/valueShowName.js';
import { getDetail as getDataDetail, getList, getUploadUrl } from '@/api/dataAccess.js';
import { getModelFieldList, getDetail, getModelList, getCompletedJson } from '@/api/model.js';
import { baseUrl } from '@/api/config.js';

export default {
	data() {
		return {
			urlQuery: {},
			details: {},
			tableFdList: [],
			detailList: [],
			detailsKey: [],
			modelDetail: {},
			previewImageList: [],
			// 判断是否图片的后缀
			imgList: ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'tif'],
			// 子表
			subTableList: [],
			modelSubTableDetail: {},
			subTableFieldList: [],
			// 下载
			downSuccessShow: false,
			downSuccessStatus: '下载成功，下载路径为：'
		};
	},
	mixins: [valueShowName],
	async onLoad(option) {
		this.urlQuery = option;
		await this.getFieldInfo();
		await this.getDetails();
		await this.getSubTableModelId();
	},
	methods: {
		// 关闭下载成功弹窗
		downSuccessClose() {
			this.downSuccessShow = false;
		},
		// 下载
		handleDownload(url) {
			const that = this;
			// #ifndef H5
			that.downSuccessStatus = `下载中，请稍等...`;
			this.downSuccessShow = true;
			uni.downloadFile({
				url: url,
				success: res => {
					if (res.statusCode === 200) {
						uni.saveFile({
							tempFilePath: res.tempFilePath,
							success: function(res) {
								const description = res.savedFilePath;
								that.downSuccessStatus = `下载成功，存储路径为: ${description}`;
							},
							fail: err => {
								that.downSuccessStatus = `存储文件失败`;
							}
						});
					} else {
						that.downSuccessStatus = `下载失败，错误码：${res.statusCode}`;
					}
				},
				fail: err => {
					that.downSuccessStatus = `下载失败`;
				}
			});
			// #endif
			// #ifdef H5
			window.open(url);
			// #endif
		},
		// 打开预览
		previewOpen(src) {
			this.$refs.previewImage.open(src);
		},
		// 获取子表数据
		async getSubTableModelId() {
			// 获取模型详情
			const {
				data: { data: detail }
			} = await getDetail({ id: this.urlQuery.modelId });
			this.modelDetail = detail;
			if (!this.modelDetail.sub_table) return;
			const {
				data: { data: modelList }
			} = await getModelList();
			// 获取子表模型详情
			this.modelSubTableDetail =
				modelList.filter(model => {
					return model.code == this.modelDetail.sub_table;
				})[0] ?? {};
			// 请求字段
			const { data } = await getCompletedJson({
				id: this.modelSubTableDetail.id
			});
			this.subTableFieldList = data.formRules;
			// 使用mixin方法（获取字段api数据）
			await this.getFieldApiData(this.subTableFieldList);
			// 请求数据
			const sendObj = {
				code: this.modelSubTableDetail.code,
				fid: this.urlQuery.id,
				page: 1,
				page_size: 999999
			};
			const {
				data: {
					data: { list: dataList }
				}
			} = await getList(sendObj);
			this.subTableList = dataList;
		},
		// 请求字段
		async getFieldInfo() {
			const {
				data: { data }
			} = await getModelFieldList({ model_id: this.urlQuery.modelId });
			const newData = data
				.map(fieldObj => {
					fieldObj.attr_json = JSON.parse(fieldObj.attr_json);
					return fieldObj;
				})
				.reverse();
			const detailShowData = newData.filter(fieldObj => {
				return fieldObj.detail_hide == '0';
			});
			this.tableFdList = detailShowData.map(item => item.attr_json);
			// 使用mixin方法（获取字段api数据）
			this.getFieldApiData(this.tableFdList);
		},
		// 请求详情
		async getDetails() {
			const sendObj = {
				code: this.urlQuery.code,
				id: this.urlQuery.id
			};
			const {
				data: { data }
			} = await getDataDetail(sendObj);
			this.details = data;
			if (this.details.id) {
				delete this.details.id;
			}
			this.detailsKey = Object.keys(data);
			// 详情字段title与value数据处理
			for (let jsonItem of this.tableFdList) {
				for (let field of this.detailsKey) {
					if (jsonItem.field == field) {
						const obj = {
							name: jsonItem.title,
							value: this.details[field],
							field: jsonItem.field,
							type: jsonItem.type,
							props: jsonItem.props,
							info: jsonItem.info
						};
						if (obj.type == 'upload') {
							if (obj.value) {
								const imgUrls = obj.value.split(',');
								for (let index in imgUrls) {
									if (imgUrls[index].indexOf('/') == -1) {
										try {
											// 请求图片地址
											const {
												data: { data }
											} = await getUploadUrl({
												code: this.urlQuery.code,
												duw1mcpd9pmvh: imgUrls[index]
											});
											if (data.length) {
												imgUrls[index] = data[0].rrq1mcpdb3cxa;
											} else {
												imgUrls[index] = '';
											}
										} catch (err) {
											imgUrls[index] = '';
										}
									}
									if (imgUrls[index] != '') {
										imgUrls[index] = `${baseUrl}${imgUrls[index].substring(1)}`;
										// 查看测试效果
										// imgUrls[index] = `https://tianshui.ciciiot.com/${imgUrls[index].substring(1)}`;
										// 预览图片数据
										this.previewImageList.push(imgUrls[index]);
									}
								}
								obj.value = imgUrls;
							} else {
								obj.value = [];
							}
						}
						if (jsonItem.children != undefined) {
							obj.children = jsonItem.children;
						}
						this.detailList.push(obj);
						console.log("detailList ================>",this.detailList)
					}
				}
			}
		}
	}
};
</script>

<style lang="scss">
.detail-cont {
	.row {
		padding: 10rpx 0;
	}
}
.roc-image {
	margin: 10rpx 10rpx 0 0;
	width: 160rpx;
	height: 160rpx;
}
// 子表
.sub-table-main {
	min-height: 388rpx;
}
.line {
	height: 10rpx;
	background-color: #dddddd;
	margin: 20rpx 0;
}
.title-box {
	display: flex;
	justify-content: space-between;
	align-items: center;
	.sub-table-title {
		font-size: 30rpx;
	}
}
.sub-table-cont {
	min-height: 60rpx;
	.row-box {
		display: flex;
		justify-content: space-between;
		padding: 30rpx 0;
		&.cont {
			padding-right: 60rpx;
		}
		.text {
			margin: 0 10rpx;
		}
	}
	.name {
		margin-right: 10rpx;
	}
	.content {
		display: flex;
		flex-wrap: wrap;
		.text {
			width: 50%;
			padding: 30rpx 0;
		}
	}
}
.image-box{
	display: flex;
	flex-wrap: wrap;
}
</style>
